﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.IO.Compression;
using System.Web;

namespace GoodMan.Portal.WebLogic
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class CompressAttribute : ActionFilterAttribute
    {
        const CompressionMode compress = CompressionMode.Compress;
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                HttpRequestBase request = filterContext.HttpContext.Request;
                HttpResponseBase response = filterContext.HttpContext.Response; string acceptEncoding = request.Headers["Accept-Encoding"];
                if (acceptEncoding == null)
                    return;

                if (acceptEncoding.ToLower().Contains("gzip"))
                {
                    response.Filter = new GZipStream(response.Filter, compress);
                    response.AppendHeader("Content-Encoding", "gzip");
                }
                else if (acceptEncoding.ToLower().Contains("deflate"))
                {
                    response.Filter = new DeflateStream(response.Filter, compress);
                    response.AppendHeader("Content-Encoding", "deflate");
                }
            }
            catch
            {
                return;
            }
        }
    }
}
